package com.jinlejia.erp.ui.house;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.BuildingBean;
import com.jinlejia.erp.bean.FloorBean;
import com.jinlejia.erp.bean.RoomBean;
import com.jinlejia.erp.bean.UnitBean;
import com.jinlejia.erp.databinding.FragmentApplyHouseBinding;
import com.jinlejia.erp.ui.common.ImageViewPagerActivity;
import com.jinlejia.erp.ui.common.MainActivity;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SheetSelectEt;
import com.jinlejia.erp.ui.common.SheetWheelFloorHouse;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.UploadPictureOnly;
import com.jinlejia.erp.widget.image.UploadImageView;
import com.weight.CustomToast;
import com.weight.IconToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import top.zibin.luban.LubanZ;

/**
 * A simple {@link Fragment} subclass.
 * 申请房间
 */
public class ApplyHouseFragment extends Fragment {
    private String houseName;
    private String housecode;
    private Http http;
    private JSONObject jsonObject = new JSONObject();
    private String unitTotal;//所在楼栋总单元数
    private int isActual; //是否跃层
    private String  yStart;//跃前
    private String yEnd;//跃后

    //梯户数据字典
    private ArrayList<Map<String,Object>> floordic = new ArrayList<>();
    private ArrayList<Map<String,Object>> housedic = new ArrayList<>();

    //房屋地址图片请求码
    private int HOUSE_ADDRESS = 100;

    //楼栋号图片请求码
    private int LOUDONG_NUMBER = 101;
    //单元号图片请求码
    private int DANYUAN_NUMBER = 102;
    //房门号图片请求码
    private int FANGMEN_NUMBER = 103;
    //所在单元全部房号报箱图片请求码
    private int HOUSE_NUMBER_ALL = 104;

    private ProgressDialog progressDialog;


    public ApplyHouseFragment() {
        // Required empty public constructor
    }

    private FragmentApplyHouseBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_apply_house, container, false);
        binding = DataBindingUtil.bind(view);
        binding.setClickfragment(this);
        //网络请求梯户字典
        getDiction();
        progressDialog = new ProgressDialog(getContext(), "请稍后...");
        //初始化网络请求类
        http = new Http(getContext());
        //页面初加载radiobutton的默认选中
        initRadio();
        //接收楼盘名称并展示
        Intent intent = getActivity().getIntent();
        houseName = intent.getStringExtra("houseName");
        housecode = intent.getStringExtra("housecode");
        binding.houseName.setText(houseName);

        binding.tvNumberUnits.setRawInputType(Configuration.KEYBOARD_QWERTY);
        binding.tvNumberHouse.setRawInputType(Configuration.KEYBOARD_QWERTY);
        binding.tvFloorall.setRawInputType(Configuration.KEYBOARD_QWERTY);

        binding.uploadHouseAddress.setListener(new InnerListener(this,HOUSE_ADDRESS));

        binding.uploadLoudongnumber.setListener(new InnerListener(this,LOUDONG_NUMBER));

        binding.uploadDanyuannumber.setListener(new InnerListener(this,DANYUAN_NUMBER));

        binding.uploadFangmennumber.setListener(new InnerListener(this,FANGMEN_NUMBER));

        binding.uploadAll.setListener(new InnerListener(this,HOUSE_NUMBER_ALL));

        return view;
    }


    /***
     * 初始化显示
     */
    private void initRadio() {
        binding.rbHave.setChecked(true);
        binding.phoneHouseAddressLinear.setVisibility(View.VISIBLE);
        binding.btPullHave.setVisibility(View.VISIBLE);
        binding.phoneLine1.setVisibility(View.GONE);
        binding.phoneLine2.setVisibility(View.GONE);
        binding.btPullHavenot.setVisibility(View.GONE);
    }

    /***
     * 是否有房本单选监听
     */
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rbHave) {
            binding.phoneHouseAddressLinear.setVisibility(View.VISIBLE);
            binding.btPullHave.setVisibility(View.VISIBLE);
            binding.phoneLine1.setVisibility(View.GONE);
            binding.phoneLine2.setVisibility(View.GONE);
            binding.btPullHavenot.setVisibility(View.GONE);
            binding.uploadFangmennumber.deleUrlMessage();
            binding.uploadDanyuannumber.deleUrlMessage();
            binding.uploadLoudongnumber.deleUrlMessage();
            binding.uploadAll.deleUrlMessage();
        } else if (checkedId == R.id.rbHavenot) {
            binding.phoneHouseAddressLinear.setVisibility(View.GONE);
            binding.btPullHave.setVisibility(View.GONE);
            binding.btPullHavenot.setVisibility(View.VISIBLE);
            binding.phoneLine1.setVisibility(View.VISIBLE);
            binding.phoneLine2.setVisibility(View.VISIBLE);
            binding.uploadHouseAddress.deleUrlMessage();
            binding.scrollView.post(new Runnable() {
                @Override
                public void run() {
                    binding.scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
        }
    }

    /***
     *跃层点击事件
     */
    public void yueFloorOnclick(View view) {
        yueFloorDialog();
    }

    /***
     * 所在楼栋点击事件
     */
    public void loudongOnclick(View view){
        binding.tvStoriedBuilding.setTag(null);
        binding.tvStoriedBuilding.setText(null);
        http.queryBuildingList(housecode, new Http.QueryBuildingCallBack() {
            @Override
            public void onQueryBuilding(List<BuildingBean> beans) {
                if (beans!=null){
                    ArrayList<Map<String,Object>> maps = new ArrayList<>();
                    for (BuildingBean buildingBean : beans) {
                        Map<String,Object> map = new HashMap<>();
                        map.put("valueName",buildingBean.getBuildingNo());
                        map.put("buildingCode",buildingBean.getBuildingCode());
                        map.put("unitTotal",buildingBean.getUnitTotal());
                        maps.add(map);
                    }
                    final SheetSelectEt sheetSelectEtLoudong = new SheetSelectEt(getContext(),maps);
                    sheetSelectEtLoudong.setView(new EditText(getContext()));
                    sheetSelectEtLoudong.show();
                    sheetSelectEtLoudong.setCancelable(true);
                    sheetSelectEtLoudong.setOnSelectListener(new SheetSelectEt.OnSelectListener() {
                        @Override
                        public void select(Object o) {
                            Map<String, Object> map = (Map<String, Object>) o;
                            sheetSelectEtLoudong.dismiss();
                            binding.tvStoriedBuilding.setText(map.get("valueName").toString());
                            binding.tvStoriedBuilding.setTag(map.get("buildingCode").toString());
                            unitTotal = map.get("unitTotal").toString();
                            if (unitTotal.equals("")){
                                binding.tvNumberUnits.setFocusable(true);
                                binding.tvNumberUnits.setFocusableInTouchMode(true);
                                binding.tvNumberUnits.setHint("请输入总数单元数");
                            }else{
                                binding.tvNumberUnits.setText(unitTotal);
                                binding.tvNumberUnits.setFocusable(true);
                                binding.tvNumberUnits.setFocusableInTouchMode(true);
                                binding.tvNumberUnits.setHint(null);
                            }
                        }
                    });

                    sheetSelectEtLoudong.setOnSureListener(new SheetSelectEt.OnSureListener() {
                        @Override
                        public void select(String name) {
                            if (TextUtils.isEmpty(name)){
                                CustomToast.showToast(getContext(),"您还没输入楼栋信息",1500);
                            }else{
                                binding.tvStoriedBuilding.setText(name);
                                binding.tvNumberUnits.setFocusable(true);
                                binding.tvNumberUnits.setFocusableInTouchMode(true);
                                binding.tvNumberUnits.setHint("请输入总数单元数");
                                sheetSelectEtLoudong.dismiss();
                            }



                        }
                    });
                }
            }
        });
    }



    /***
     * 所在楼栋总单元数点击事件
     */
    public void danyuanallOnclick(View view){
        if (TextUtils.isEmpty(binding.tvStoriedBuilding.getText())) {
            CustomToast.showToast(getContext(), "请先选择所在楼栋", 1500);
            return;
        }
    }


    /***
     * 所在单元点击事件
     */
    public void danyuanOnclick(View view){
        if (TextUtils.isEmpty(binding.tvStoriedBuilding.getText())) {
            CustomToast.showToast(getContext(), "请先选择楼栋", 1500);
            return;
        }
        binding.tvUnits.setText(null);
        binding.tvUnits.setTag(null);
        String key = String.valueOf(binding.tvStoriedBuilding.getTag());
        http.queryEstateListByBuildingCode(key, new Http.UnitCallBack() {
            @Override
            public void onUnitResult(final List<UnitBean> beans) {
                if (beans != null) {
                    ArrayList<Map<String, Object>> maps = new ArrayList<>();
                    for (UnitBean unitBean : beans) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("unitCode", unitBean.getUnitCode());
                        map.put("valueName", unitBean.getUnitNo());
                        map.put("allFloor", unitBean.getAllFloor());
                        maps.add(map);
                    }
                    final SheetSelectEt sheetSelectEtDanyuan= new SheetSelectEt(getContext(),maps);
                    sheetSelectEtDanyuan.setView(new EditText(getContext()));
                    sheetSelectEtDanyuan.show();
                    sheetSelectEtDanyuan.setCancelable(true);

                    sheetSelectEtDanyuan.setOnSelectListener(new SheetSelectEt.OnSelectListener() {
                        @Override
                        public void select(Object o) {
                            Map<String, Object> map = (Map<String, Object>) o;
                            String valueName = (String) map.get("valueName");
                            String allFloor = map.get("allFloor").toString();
                            String unitCode = map.get("unitCode").toString();
                            binding.tvUnits.setText(valueName);
                            binding.tvUnits.setTag(unitCode);
                            if (allFloor.equals("")){
                                binding.tvFloorall.setFocusable(true);
                                binding.tvFloorall.setFocusableInTouchMode(true);
                                binding.tvFloorall.setHint("请输入总楼层数");
                            }else{
                                binding.tvFloorall.setFocusable(true);
                                binding.tvFloorall.setFocusableInTouchMode(true);
                                binding.tvFloorall.setHint(null);
                                binding.tvFloorall.setText(allFloor);
                            }
                            sheetSelectEtDanyuan.dismiss();
                        }
                    });

                    sheetSelectEtDanyuan.setOnSureListener(new SheetSelectEt.OnSureListener() {
                        @Override
                        public void select(String name) {
                            if (TextUtils.isEmpty(name)){
                                CustomToast.showToast(getContext(),"您还没输入单元信息",1500);
                            }else{
                                binding.tvUnits.setText(name);
                                binding.tvFloorall.setFocusable(true);
                                binding.tvFloorall.setFocusableInTouchMode(true);
                                binding.tvFloorall.setHint("请输入总楼层数");
                                sheetSelectEtDanyuan.dismiss();
                            }

                        }
                    });

                }
            }
        });
    }


    /***
     * 所在楼层点击事件
     */
    public void floorOnclick(View view){
        binding.tvFloor.setText(null);
        binding.tvFloor.setTag(null);
        String key = String.valueOf(binding.tvUnits.getTag());
        http.queryFloorList(key, new Http.QueryFloorListCallBack() {
            @Override
            public void onFloorResult(List<FloorBean> beans) {
                if (beans!=null) {
                    ArrayList<Map<String, Object>> maps = new ArrayList<>();
                    for (FloorBean floorBean : beans) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("valueName", floorBean.getActualFloor());
                        map.put("floorCode", floorBean.getFloorCode());
                        maps.add(map);
                    }

                    final SheetSelectEt sheetSelectEtFloor= new SheetSelectEt(getContext(),maps);
                    sheetSelectEtFloor.setView(new EditText(getContext()));
                    sheetSelectEtFloor.show();
                    sheetSelectEtFloor.setCancelable(true);

                    sheetSelectEtFloor.setOnSelectListener(new SheetSelectEt.OnSelectListener() {
                        @Override
                        public void select(Object o) {
                            Map<String, Object> map = (Map<String, Object>) o;
                            String valueName = (String) map.get("valueName");
                            String floorCode = map.get("floorCode").toString();
                            binding.tvFloor.setText(valueName);
                            binding.tvFloor.setTag(floorCode);
                            sheetSelectEtFloor.dismiss();
                        }
                    });

                    sheetSelectEtFloor.setOnSureListener(new SheetSelectEt.OnSureListener() {
                        @Override
                        public void select(String name) {
                            if (TextUtils.isEmpty(name)){
                                CustomToast.showToast(getContext(),"您还没输入楼层信息",1500);
                            }else{
                                binding.tvFloor.setText(name);
                                sheetSelectEtFloor.dismiss();
                            }

                        }
                    });

                }
            }
        });
    }

    /***
     * 梯户点击事件
     */
    public void floorHouseOnclick(View view){
        SheetWheelFloorHouse sheetWheelFloorHouse =new SheetWheelFloorHouse(getContext(),floordic,housedic);
        sheetWheelFloorHouse.show();
        sheetWheelFloorHouse.setOnSelectListener(new SheetWheelFloorHouse.OnSelectListener() {
            @Override
            public void select(Map<String, Integer> map) {
                jsonObject.putAll(map);
                binding.tvLaddeHousehold.setText(map.get("elevators")+"梯"+map.get("households")+"户");
            }
        });
    }

    /***
     * 有房本提交事件
     */
    public void btHaveOnclick(View view){
        jsonObject.put("type",1);//申請类型
        jsonObject.put("isProperty",1);//是否有房本
        jsonObject.put("isActual",isActual);//是否跃层
        if (isActual==1){
            //添加跃层
            jsonObject.put("actualFloorFirst",yStart);
            jsonObject.put("actualFloorSecond",yEnd);
        }
        jsonObject.put("reName",houseName);//楼盘名称
        jsonObject.put("buildingNo",binding.tvStoriedBuilding.getText().toString());//座栋名称
        if (!TextUtils.isEmpty(binding.tvNumberUnits.getText().toString())){jsonObject.put("unitTotal",Integer.parseInt(binding.tvNumberUnits.getText().toString()));}//所在单元总数
        jsonObject.put("unitNo",binding.tvUnits.getText().toString());//单元号
        jsonObject.put("roomNo",binding.tvNumberHouse.getText().toString());//房间号
        jsonObject.put("tabFloor",binding.tvFloor.getText().toString());//所在楼层
        if (!TextUtils.isEmpty(binding.tvFloorall.getText().toString())){jsonObject.put("floorTotal",Integer.parseInt(binding.tvFloorall.getText().toString()));}//总楼层
        jsonObject.put("propertyImage",binding.uploadHouseAddress.getServerUrl());

        if (TextUtils.isEmpty(binding.tvStoriedBuilding.getText().toString())){
            CustomToast.showToast(getContext(), "请选择或者输入所在楼栋", 1500);
        }else if (TextUtils.isEmpty(binding.tvUnits.getText().toString())){
            CustomToast.showToast(getContext(), "请输入或选择所在单元", 1500);
        }else if (TextUtils.isEmpty(binding.tvNumberHouse.getText().toString())){
            CustomToast.showToast(getContext(), "请输入所在房号", 1500);
        }else if (TextUtils.isEmpty(binding.tvFloor.getText().toString())){
            CustomToast.showToast(getContext(), "请选择或者输入楼层", 1500);
        }else if (TextUtils.isEmpty(binding.tvFloorall.getText().toString())){
            CustomToast.showToast(getContext(), "请输入总楼层", 1500);
        }else if (TextUtils.isEmpty(binding.tvYuefloor.getText().toString())){
            CustomToast.showToast(getContext(), "请输入跃层信息", 1500);
        }else if (TextUtils.isEmpty(binding.tvLaddeHousehold.getText().toString())){
            CustomToast.showToast(getContext(), "请选择梯户", 1500);
        }else if (TextUtils.isEmpty(jsonObject.getString("propertyImage"))){
            CustomToast.showToast(getContext(), "请上传房屋地址照片", 1500);
        }else {
            submit();
        }
    }


    /***
     * 无房本提交事件
     */
    public void btHavenotOnclick(View view){
        jsonObject.put("type",1);//申請类型
        jsonObject.put("isProperty",2);//是否有房本
        jsonObject.put("isActual",isActual);//是否跃层
        if (isActual==1){
            //添加跃层
            jsonObject.put("actualFloorFirst",yStart);
            jsonObject.put("actualFloorSecond",yEnd);
        }
        jsonObject.put("reName",houseName);//楼盘名称
        jsonObject.put("buildingNo",binding.tvStoriedBuilding.getText().toString());//座栋名称
        if (!TextUtils.isEmpty(binding.tvNumberUnits.getText().toString())){jsonObject.put("unitTotal",Integer.parseInt(binding.tvNumberUnits.getText().toString()));}//所在单元总数
        jsonObject.put("unitNo",binding.tvUnits.getText().toString());//单元号
        jsonObject.put("roomNo",binding.tvNumberHouse.getText().toString());//房间号
        jsonObject.put("tabFloor",binding.tvFloor.getText().toString());//所在楼层
        if (!TextUtils.isEmpty(binding.tvFloorall.getText().toString())){jsonObject.put("floorTotal",Integer.parseInt(binding.tvFloorall.getText().toString()));}//总楼层
        jsonObject.put("buildingImage",binding.uploadLoudongnumber.getServerUrl());//楼栋号照片
        jsonObject.put("unitImage",binding.uploadDanyuannumber.getServerUrl());//单元号照片
        jsonObject.put("roomImage",binding.uploadFangmennumber.getServerUrl());//房门号照片
        jsonObject.put("mailboxImage",binding.uploadAll.getServerUrl());//所在单元全部房号报箱照片


        if (TextUtils.isEmpty(binding.tvStoriedBuilding.getText().toString())){
            CustomToast.showToast(getContext(), "请选择或者输入所在楼栋", 1500);
        }else if (TextUtils.isEmpty(binding.tvUnits.getText().toString())){
            CustomToast.showToast(getContext(), "请输入或选择所在单元", 1500);
        }else if (TextUtils.isEmpty(binding.tvNumberHouse.getText().toString())){
            CustomToast.showToast(getContext(), "请输入所在房号", 1500);
        }else if (TextUtils.isEmpty(binding.tvFloor.getText().toString())){
            CustomToast.showToast(getContext(), "请选择或者输入楼层", 1500);
        }else if (TextUtils.isEmpty(binding.tvFloorall.getText().toString())){
            CustomToast.showToast(getContext(), "请输入总楼层", 1500);
        }else if (TextUtils.isEmpty(binding.tvYuefloor.getText().toString())){
            CustomToast.showToast(getContext(), "请输入跃层", 1500);
        }else if (TextUtils.isEmpty(binding.tvLaddeHousehold.getText().toString())){
            CustomToast.showToast(getContext(), "请选择梯户", 1500);
        }else if (TextUtils.isEmpty(jsonObject.getString("buildingImage"))){
            CustomToast.showToast(getContext(), "请上传楼栋号照片", 1500);
        }else if (TextUtils.isEmpty(jsonObject.getString("unitImage"))){
            CustomToast.showToast(getContext(), "请上传单元号照片", 1500);
        }else {
            submit();
        }


    }

    /***
     * 保存信息请求
     */
    private void submit() {
        progressDialog.show();
        OkHttpUtils.postString()
                .url(ApiConfig.SAVE_LOUPAN)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(getContext(), response)) {
                            IconToast.showToast(getContext(), R.mipmap.ic_success, "提交成功", 1500);
                            Intent intent = new Intent(getContext(), MainActivity.class);
                            getContext().startActivity(intent);
                        }
                    }
                });
    }


    /***
     * 跃层弹出框
     */
    public void yueFloorDialog() {
        final Dialog bgSetDialog = new Dialog(getContext(), R.style.BottomDialogStyle);
        //填充对话框的布局
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_thermocline, null);
        //初始化控件
        final RadioButton rbYes = view.findViewById(R.id.rbYes);
        RadioButton rbNo = view.findViewById(R.id.rbNo);
        TextView tvSure = view.findViewById(R.id.tvSure);
        final EditText etYstart = view.findViewById(R.id.etYstart);
        final EditText etYend = view.findViewById(R.id.etYend);
        rbNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                rbYes.setChecked(true);
                binding.tvYuefloor.setText("否");
                isActual = 2;
                bgSetDialog.dismiss();

            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               yStart = etYstart.getText().toString();
               yEnd = etYend.getText().toString();
                if (TextUtils.isEmpty(yStart)||TextUtils.isEmpty(yEnd)){
                    CustomToast.showToast(getContext(),"您还没有输入跃层信息",1500);
                }else{
                    if (Integer.parseInt(yStart)>= Integer.parseInt(yEnd)){
                        CustomToast.showToast(getContext(),"跃层请按从低到高的顺序填写！",1500);
                        return;
                    }
                    binding.tvYuefloor.setText(yStart + "跃" + yEnd);
                    isActual = 1;
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm!=null){
                        imm.hideSoftInputFromWindow(bgSetDialog.getWindow().getDecorView().getWindowToken(), 0);
                    }
                    bgSetDialog.dismiss();


                }
            }
        });
        //将布局设置给Dialog
        bgSetDialog.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = bgSetDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (getActivity().getWindowManager().getDefaultDisplay().getWidth());
        lp.height = (int) (getActivity().getWindowManager().getDefaultDisplay().getWidth() * 0.3);
        dialogWindow.setAttributes(lp); //将属性设置给窗体
        bgSetDialog.setCancelable(true);
        bgSetDialog.show();//显示对话框
    }

    /***
     * 网络请求梯户数据字典
     */
    public void getDiction() {
        OkHttpUtils.postString()
                   .url(ApiConfig.FLOOR_HOUSE_TRADIONG_AREA)
                   .mediaType(MediaType.parse("application/json; charset=utf-8"))
                   .content(new JSONObject().toString())
                   .build()
                   .execute(new MapCallBack() {
                       @Override
                       public void onError(Call call, Exception e, int id) {
                           e.printStackTrace();
                       }

                       @Override
                       public void onResponse(Map<String, Object> response, int id) {
                           if (DataFilter.filter(getContext(),response)){
                               JSONObject data = JSON.parseObject(response.get("data").toString());
                               //梯数据字典
                               floordic = JSON.parseObject(data.getJSONArray("ti").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                               });
                               //户数据字典
                               housedic = JSON.parseObject(data.getJSONArray("hu").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                               });
                           }
                       }
                   });
    }


    /***
     *网络请求接口类
     */
    private static class Http{
        private final Context mContext;
        private Http(Context context){
            this.mContext = context;
        }

        //region 根据小区编码搜索座栋信息
        void queryBuildingList(String reCode, final QueryBuildingCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_BUILDING_LIST.concat(reCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("buildingList");
                                List<BuildingBean> beans = JSON.parseArray(list.toString(), BuildingBean.class);
                                callBack.onQueryBuilding(beans);
                            }
                        }
                    });
        }
        public interface QueryBuildingCallBack{
            void onQueryBuilding(List<BuildingBean> beans);
        }

        //endregion

        //region 根据座栋编号获取单元集合
        void queryEstateListByBuildingCode(String buildingCode,final UnitCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_UNIT_BY_BUILDING.concat(buildingCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("unitList");
                                List<UnitBean> beans = JSON.parseArray(list.toString(), UnitBean.class);
                                callBack.onUnitResult(beans);
                            }
                        }
                    });
        }

        public interface UnitCallBack{
            void onUnitResult(List<UnitBean> beans);
        }

        //endregion

        //region 根据单元编号获取楼层信息
        void queryFloorList(String unitCode,final QueryFloorListCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_FLOOR_LIST.concat(unitCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("floorList");
                                List<FloorBean> beans = JSON.parseArray(list.toString(), FloorBean.class);
                                callBack.onFloorResult(beans);
                            }
                        }
                    });
        }

        public interface QueryFloorListCallBack{
            void onFloorResult(List<FloorBean> beans);
        }
        //endregion

        //region 根据楼层编码搜索房间列表
        void queryRoomList(String floorCode,final QueryRoomListCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_ROOM_LIST.concat(floorCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if ("501".equals(String.valueOf(response.get("code")))){
                                callBack.onQueryRoomList(null);
                            }else{
                                if (DataFilter.filter(mContext,response)) {
                                    JSONObject data = JSON.parseObject(response.get("data").toString());
                                    JSONArray list = data.getJSONArray("roomList");
                                    List<RoomBean> beans = JSON.parseArray(list.toString(), RoomBean.class);
                                    callBack.onQueryRoomList(beans);
                                }
                            }


                        }
                    });
        }

        public interface QueryRoomListCallBack{
            void onQueryRoomList(List<RoomBean> beans);
        }
        //endregion


        private boolean showEmptyMessage(Map<String, Object> response){
            if ("501".equals(String.valueOf(response.get("code")))){
                if (response.get("message") != null)
                    CustomToast.showToast(mContext, response.get("message").toString(), 1500);
                return true;
            }
            return false;
        }
    }




    /***
     * 图片上传
     */
    private class InnerListener implements UploadImageView.Listener{
        private Fragment fragment;
        private int code;

        public InnerListener(Fragment fragment, int code) {
            this.fragment = fragment;
            this.code = code;
        }

        @Override
        public void onDeleteImage(UploadImageView view) {}

        @Override
        public void onChooseImage(UploadImageView view) {
            ImageSelector.builder()
                    .useCamera(true)
                    .setSingle(true)
                    .setViewImage(true)
                    .start(fragment, code);
        }

        @Override
        public void onPreviewImage(UploadImageView view, String previewUrl) {
            ArrayList<String> imgList = new ArrayList<>();
            ArrayList<String> nameList = new ArrayList<>();
            String url;
            if (binding.rbHave.isChecked()){
                //region Picture 1
                url = binding.uploadHouseAddress.getServerUrl();
                if (TextUtils.isEmpty(url)){
                    url = binding.uploadHouseAddress.getOriginalUrl();
                }else {
                    url = ApiConfig.MAGEHEADER_URL()+url;
                }
                if (!TextUtils.isEmpty(url)){
                    imgList.add(url);
                    nameList.add("房屋地址照片");
                }
            }else{
                url = binding.uploadLoudongnumber.getServerUrl();
                if (TextUtils.isEmpty(url)){
                    url = binding.uploadLoudongnumber.getOriginalUrl();
                }else {
                    url = ApiConfig.MAGEHEADER_URL()+url;
                }
                if (!TextUtils.isEmpty(url)){
                    imgList.add(url);
                    nameList.add("楼栋号照片");
                }


                url = binding.uploadDanyuannumber.getServerUrl();
                if (TextUtils.isEmpty(url)){
                    url = binding.uploadDanyuannumber.getOriginalUrl();
                }else {
                    url = ApiConfig.MAGEHEADER_URL()+url;
                }
                if (!TextUtils.isEmpty(url)){
                    imgList.add(url);
                    nameList.add("单元号照片");
                }


                url = binding.uploadFangmennumber.getServerUrl();
                if (TextUtils.isEmpty(url)){
                    url = binding.uploadFangmennumber.getOriginalUrl();
                }else {
                    url = ApiConfig.MAGEHEADER_URL()+url;
                }
                if (!TextUtils.isEmpty(url)){
                    imgList.add(url);
                    nameList.add("房门号照片");
                }


                url = binding.uploadAll.getServerUrl();
                if (TextUtils.isEmpty(url)){
                    url = binding.uploadAll.getOriginalUrl();
                }else {
                    url = ApiConfig.MAGEHEADER_URL()+url;
                }
                if (!TextUtils.isEmpty(url)){
                    imgList.add(url);
                    nameList.add("所有单元全部房号报箱照片");
                }
            }

            int position = 0;
            for (int i = 0; i < imgList.size(); i++) {
                String imgUrl = imgList.get(i);
                imgUrl = imgUrl.replace(ApiConfig.MAGEHEADER_URL(),"");
                if (TextUtils.equals(previewUrl,imgUrl)){
                    position = i+1;
                    break;
                }
            }

                Intent intent = new Intent(getActivity(), ImageViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", imgList);
                intent.putStringArrayListExtra("names", nameList);
                intent.putExtra("position",position);
                intent.putExtra("check","picture");
                getContext().startActivity(intent);

        }

        @Override
        public void onUploadImage(final UploadImageView view, String originalUrl) {
            progressDialog.show();
            ArrayList<LubanZ.LubanZImage> files = new ArrayList<>();
            LubanZ.LubanZImage image = new LubanZ.LubanZImage();
            File file = new File(originalUrl);
            if (file.exists()){
                image.setOriginalFile(file);
                files.add(image);
            }
            UploadPictureOnly pictureOnly = new UploadPictureOnly(getContext());

            pictureOnly.uoloadOnlyImage(files, new UploadPictureOnly.UploadImageCallBack() {
                @Override
                public void onUploadSuccess(String fileName, String serverUrl) {
                    if (null != progressDialog && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    view.uploadSuccess(serverUrl);
                    Log.e("wwe", "onUploadSuccess: "+serverUrl);
                }

                @Override
                public void onUploadonFail(String s) {
                    if (null != progressDialog && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    CustomToast.showToast(getContext(),"上传失败,错误码："+s,3000);
                    view.uploadFailed();
                }
            });
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && requestCode == HOUSE_ADDRESS) {
                ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                String url = list.get(0);
                binding.uploadHouseAddress.selectSuccess(url);
            }

            if (data != null && requestCode == LOUDONG_NUMBER) {
                ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                String url = list.get(0);
                binding.uploadLoudongnumber.selectSuccess(url);
            }


            if (data != null && requestCode == DANYUAN_NUMBER) {
                ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                String url = list.get(0);
                binding.uploadDanyuannumber.selectSuccess(url);
            }


            if (data != null && requestCode == FANGMEN_NUMBER) {
                ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                String url = list.get(0);
                binding.uploadFangmennumber.selectSuccess(url);
            }


            if (data != null && requestCode == HOUSE_NUMBER_ALL) {
                ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                String url = list.get(0);
                binding.uploadAll.selectSuccess(url);
            }
        }
    }
}
